package main

import (
	"fmt"
	"reflect"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

type LoginDto struct {
	Username string `json:"username" binding:"required" msg:"用户名不能为空"`
	Password string `json:"password" binding:"min=3,max=6" msg:"密码长度不能小于3大于6"`
	Email    string `json:"email" binding:"email" msg:"邮箱地址格式不正确"`
}

func GetValidMsg(err error, obj interface{}) string {
	fmt.Println("sherlock")
	getObj := reflect.TypeOf(obj)
	if errs, ok := err.(validator.ValidationErrors); ok {
		for _, e := range errs {
			if f, exist := getObj.Elem().FieldByName(e.Field()); exist {
				return f.Tag.Get("msg")
			}
		}
	}
	return err.Error()
}

func main() {
	r := gin.Default()

	r.POST("/login", func(c *gin.Context) {
		userDto := &LoginDto{}
		if err := c.ShouldBindJSON(userDto); err != nil {
			c.JSON(200, gin.H{
				"status":  "err",
				"message": GetValidMsg(err, userDto),
			})

		} else {
			c.JSON(200, gin.H{
				"status":  "change",
				"message": userDto,
			})
		}
	})
	r.Run(":8080")
}
